<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\User as UserModel;
use app\admin\validate\User as UserValidate;
use think\exception\ValidateException;
use think\Request;

class Login
{
    private  $user;
    public function __construct(UserModel $user)
    {
        $this->user = $user;
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('login');
    }

    public function login(Request $request)
    {
        $status = 0;
        $msg = "验证错误";
        if ($request->isAjax(true)){
            //获取前端提交的数据
            $data = $request->param();
            //验证数据
            try {
               validate(UserValidate::class)->check($data);
               //通过用户名查询用户数据
                $user = UserModel::where('username',$data['username'])
                    ->find();
                if ($user){
                    //验证密码
                    $passwrod = md5(md5($data['password']));
                    if ($user->password === $passwrod){
                        //定义登录状态 session;
                        session('user',[
                            'userid'=>$user->id,
                            'username'=>$user->username
                        ]);
                        $status = 1;
                        $msg = "登录成功";
                    }else{
                        $msg = "密码错误";
                    }
                }else{
                    $msg = "用户名不存在";
                }
            }catch (ValidateException $e){
                $msg = $e->getError();
            }
        }

        return ['status'=>$status,'msg'=>$msg];
    }
}
